# your_app/consumers.py
import json
import os
import uuid
import time
from fileinput import close
from os import system
from sched import scheduler
from socket import socket
from django.dispatch import Signal
from channels.exceptions import StopConsumer
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
import asyncio

from django.db import connection
from django_bootstrap5.text import text_value
from twisted.conch.client.connect import connect

from mqtt.tcp_server import device_rev_list

socket_key = {}
socket_list = []

# json数据校验
# JSON序列号函数
def serialize_to_json(obj):
    try:
        # 尝试将对象序列化为JSON字符串
        json_str = json.dumps(obj)
        return json_str
    except (TypeError, OverflowError) as e:
        # 捕获类型错误或溢出错误
        print(f"Error serializing object: {e}")
        # 可以选择返回一个错误消息、None或其他默认值
        return None
    except Exception as e:
        # 捕获其他未预料到的异常
        print(f"An unexpected error occurred: {e}")
        # 同样，可以选择返回一个错误消息、None或其他默认值
        return None

# 定义一个名为websocket_socketserver_signal的信号

class YourConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # 当WebSocket连接建立时调用
        # room_name = self.scope['url_route']['kwargs']
        #    await self.channel_layer.group_add('heartbeats', self.channel_name)
        socket_list.append(self)
        print(self)
        await self.accept()
        self.ping_task = asyncio.create_task(self.ping_loop()) #创建一个线程进行心跳包发送auth_group_permissions

    async def receive(self, text_data=None, bytes_data=None):
        # 收到客户端消息时调用
        message = text_data
        # 对message进行处理
        print(text_data)
        ws_send_data = serialize_to_json(device_rev_list)# 是正常的json
        if ws_send_data is not None:
            print("可以序列化")
            await self.send(text_data=ws_send_data)
        else:print("不可以序列化")
        await asyncio.sleep(1)


# async def send(self, text_data=None, bytes_data=None, close=False):
#     while True:
#         system_info = {
#             "system": 123,
#             "data": 124,
#         }
#         await self.send(json.dumps(system_info))
#         await asyncio.sleep(5)
    async def ping_loop(self):
        while True:
            await asyncio.sleep(5)  # 每10秒发送一次ping
            await self.send(json.dumps({"ping": "ping"}))


    async def disconnect(self, message):
        # 当连接断开时调用
        print(message)
        self.ping_task.cancel()
        # socket_list.remove(self)


#   await self.channel_layer.group_discard('heartbeats', self.channel_name)

async def websocket_disconnect(self, message):
    # 当websocket连接断开时，清理资源
    print(message)
    await self.disconnect(message['code'])
